package com.example.myapplication;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.myapplication.Helper.TodayHelper;
import com.example.myapplication.adapter.TodayAdapter;
import com.example.myapplication.bean.TodayBean;

import java.util.ArrayList;

public class TodayTripActivity extends AppCompatActivity {
    private TodayAdapter todayAdapter;
    private TodayHelper todayHelper;
    private SQLiteDatabase database;
    private ArrayList<TodayBean> dataSet = new ArrayList<TodayBean>();
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_today_trip);
        listView = findViewById(R.id.imp_list);

        //创建数据库
        todayHelper = new TodayHelper(this, "today.db", null, 1);
        database = todayHelper.getReadableDatabase();

        //查询数据库
        initdataSet();
        //展示行程列表
        todayAdapter = new TodayAdapter(TodayTripActivity.this, R.layout.today, dataSet);
        listView.setAdapter(todayAdapter);

        //单机修改事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                View updataview = LayoutInflater.from(TodayTripActivity.this).inflate(R.layout.add_today, null);
                EditText title = updataview.findViewById(R.id.t_title);
                DatePicker date = updataview.findViewById(R.id.t_date);
                TimePicker time = updataview.findViewById(R.id.t_time);
                EditText book = updataview.findViewById(R.id.t_book);
                final TodayBean todayBean = dataSet.get(position);
                title.setText(todayBean.getTitle_txt());
                //将数据库日期与时间展示到界面
                date.init(Integer.parseInt(todayBean.getYear()),Integer.parseInt(todayBean.getMonth())-1,Integer.parseInt(todayBean.getDay()),null);
                time.setHour(Integer.parseInt(todayBean.getHour()));
                time.setMinute(Integer.parseInt(todayBean.getMin()));
                book.setText(todayBean.getBook());
                new AlertDialog.Builder(TodayTripActivity.this)
                        .setIcon(R.drawable.update)
                        .setTitle("修改行程")
                        .setView(updataview)
                        .setPositiveButton("我要修改", new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String uptitle= title.getText().toString().trim();
                                String upyear = String.valueOf(date.getYear());
                                String upmonth = String.valueOf(date.getMonth()+1);
                                String upday = String.valueOf(date.getDayOfMonth());
                                String uphour = String.valueOf(time.getHour());
                                String upmin = String.valueOf(time.getMinute());
                                String upbook= book.getText().toString().trim();
                                //操作数据库
                                ContentValues values=new ContentValues();
                                values.put("title", uptitle);
                                values.put("year", upyear);
                                values.put("month", upmonth);
                                values.put("day", upday);
                                values.put("hour", uphour);
                                values.put("min", upmin);
                                values.put("book", upbook);
                                long result=database.update("today",values,"title=?", new String[]{todayBean.getTitle_txt()});
                                if (result==1){
                                    TodayBean todayBean1=new TodayBean(uptitle,upyear, upmonth,upday, uphour, upmin,upbook);
                                    //替换原来内容，更新单行视图
                                    dataSet.set(position, todayBean1);
                                    todayAdapter.notifyDataSetChanged();
                                    Toast.makeText(TodayTripActivity.this, "修改成功!", Toast.LENGTH_LONG).show();
                                }else {
                                    Toast.makeText(TodayTripActivity.this, "修改失败~", Toast.LENGTH_LONG).show();
                                }
                            }
                        }).setNegativeButton("再想想", null)
                        .create()
                        .show();
            }
        });

        //长单击删除事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                final TodayBean todayBean=dataSet.get(position);
                new AlertDialog.Builder(TodayTripActivity.this)
                        .setIcon(R.drawable.del)
                        .setTitle("删除")
                        .setMessage("你要删除行程为"+todayBean.getTitle_txt()+"的提醒吗？")
                        .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                long sql = database.delete("today", "title=?", new String[]{todayBean.getTitle_txt()});
                                if (sql == 1) {
                                    //删除成功
                                    dataSet.remove(position);
                                    todayAdapter.notifyDataSetChanged();
                                    Toast.makeText(TodayTripActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
                                } else {
                                    //删除失败
                                    Toast.makeText(TodayTripActivity.this, "删除失败！", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("我再想想", null)
                        .create()
                        .show();
                return true;
            }
        });
    }

    /**
     * 查询列表数据(数据库中)
     **/
    public void initdataSet() {
        String sql = "select * from today";
        Cursor cursor = database.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            Log.v("title", cursor.getString(1));
            Log.v("date", cursor.getString(2) + "年" + cursor.getString(3) + "月" + cursor.getString(4) + "日");
            Log.v("time", cursor.getString(5) + "时" + cursor.getString(6) + "分");
            Log.v("book", cursor.getString(7));
            TodayBean todayBean = new TodayBean(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6),cursor.getString(7));
            dataSet.add(todayBean);
        }
        Log.v("result", cursor.toString());
    }


    /**
     * 新增事项按钮事件，自定义弹窗
     **/
    public void addtoday(View view) {
        View layout = LayoutInflater.from(TodayTripActivity.this).inflate(R.layout.add_today, null);
        EditText title = layout.findViewById(R.id.t_title);
        DatePicker date = layout.findViewById(R.id.t_date);
        TimePicker time = layout.findViewById(R.id.t_time);
        EditText book = layout.findViewById(R.id.t_book);
        new AlertDialog.Builder(TodayTripActivity.this)
                .setIcon(R.drawable.add)
                .setTitle("新增主题")
                .setView(layout)
                .setPositiveButton("我要添加", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String title_t = title.getText().toString().trim();
                        Log.v("title", title_t);
                        String year = String.valueOf(date.getYear());
                        String month = String.valueOf(date.getMonth()+1);
                        String day = String.valueOf(date.getDayOfMonth());
                        Log.v("date", year + "年" + month + "月" + day + "日");
                        String hour = String.valueOf(time.getHour());
                        String min = String.valueOf(time.getMinute());
                        Log.v("time", hour + "点" + min + "分");
                        String book_t = book.getText().toString().trim();
                        Log.v("book", book_t);
                        //判断标题是否为空
                        if (!TextUtils.isEmpty(title_t)) {
                            //不为空就存入数据库
                            ContentValues values = new ContentValues();
                            values.put("title", title_t);
                            values.put("year", year);
                            values.put("month", month);
                            values.put("day", day);
                            values.put("hour", hour);
                            values.put("min", min);
                            values.put("book", book_t);
                            long result = database.insert("today", null, values);
                            if (result != -1) {
                                //添加成功
                                Toast.makeText(TodayTripActivity.this, "提醒设置成功！", Toast.LENGTH_LONG).show();
                                TodayBean todayBean=new TodayBean(title_t, year, month,day, hour, min,book_t);
                                dataSet.add(todayBean);
                                todayAdapter.notifyDataSetChanged();
                            } else {
                                //添加失败
                                Toast.makeText(TodayTripActivity.this, "提醒设置失败~", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(TodayTripActivity.this, "还没添加主题哦~", Toast.LENGTH_LONG).show();
                        }

                    }
                }).setNegativeButton("考虑一下", null)
                .create()
                .show();
    }

}